<!--
 * @Descripttion:挂账回款右边布局卡片
-->
<template>
  <div>
    <div class="onAccount-card-box" :class="orderDetailData ? 'show' : 'hide'">
      <!-- Loading 骨架屏 -->
      <div v-if="loading || !orderDetailData" class="skeleton-container">
        <el-skeleton :rows="20" animated />
      </div>

      <!-- 实际内容（对齐老项目结构） -->
      <div v-else>
        <!-- 餐厅名字 -->
        <div class="title">{{ shopName }}</div>
        <div class="description">【账单信息】</div>

        <!-- 桌台 + 收银员 -->
        <div class="desc-item flex-start" v-if="deskListExists">
          <div>
            桌台：<span class="desk-item lineHeight20">{{ computedDeskName }}</span>
          </div>
          <span>{{ clerkName }}</span>
        </div>

        <!-- 单号 -->
        <div class="desc-item flex-start">
          <div>单号：{{ orderId }}</div>
          <span></span>
        </div>

        <!-- 结账时间 -->
        <div class="desc-item flex-start">
          <div>结账时间：{{ createTime }}</div>
          <span></span>
        </div>

        <!-- 表头 -->
        <div class="desc-item" style="margin-top: 20px">
          <div>菜品名称</div>
          <div>数量</div>
          <div>总金额</div>
        </div>
        <div class="desc-line"></div>

        <!-- 菜品列表 -->
        <template v-if="foodListExists">
          <div
            class="good-list-box"
            v-for="food in orderDetailData.detail.foodList"
            :key="food.desk_id"
          >
            <div class="good-item align-items-start">
              <div class="good-name lineHeight20">{{ food.name }}</div>
              <div>￥{{ food.money }}</div>
              <div>{{ food.num }}份</div>
            </div>
            <div class="good-sku-item" v-if="dealFoodSkuDescFun(food)">
              ({{ dealFoodSkuDescFun(food) }})
            </div>
          </div>
          <div class="desc-line"></div>
        </template>

        <!-- 桌台服务费 -->
        <div class="desc-item">
          <div>桌台服务费</div>
          <span></span>
          <div>{{ priceInfo.serviceMoney }}</div>
        </div>
        <!-- 应收 -->
        <div class="desc-item">
          <div>应收</div>
          <span></span>
          <div>{{ priceInfo.payMoney }}</div>
        </div>

        <div class="desc-line"></div>

        <!-- 实收  -->
        <div class="desc-item align-items-start flex-start">
          <div>实收：</div>
          <div>
            <span>{{ payMethod() }}：{{ priceInfo.payMoney }}</span>
          </div>
        </div>

        <!-- 实收明细 + 挂账明细 -->
        <template v-if="payInfo.length > 1 || creditList.length > 0">
          <div class="desc-item"><div>实收明细</div></div>
          <div
            class="desc-item align-items-start flex-start"
            v-for="item in payInfo"
            :key="item.pay_method + (item.type || '')"
          >
            <div>
              {{
                payMethodEnum[item.pay_method + (item.type ? item.type : '')] ||
                payMethodEnum[item.pay_method]
              }}:
            </div>
            <span>{{ item.money }}</span>
          </div>
          <template v-for="item in creditList" :key="item.name + item.type">
            <div class="desc-item align-items-start flex-start">
              <div>{{ item.type == 1 ? '企业挂账' : '个人挂账' }}:</div>
              <span>{{ item.money }}</span>
            </div>
            <div class="desc-item align-items-start flex-start">
              <div>{{ item.type == 1 ? '挂账企业' : '担保人' }}:</div>
              <span>{{ item.name }}</span>
            </div>
          </template>
        </template>

        <!-- 餐厅地址/电话/技术支持 -->
        <div class="address-phone-box">
          <div>餐厅地址：{{ shopAddress }}</div>
          <div>餐厅电话：{{ shopPhone }}</div>
          <div>技术支持：贵州一粒米科技餐饮软件服务有限公司</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { dealAssignDataFunction, fetchObjectDeepAttrValue } from '@/utils/toolsValidate'
import { ticketDetail as orderCreditDetail } from '@/api/statistics'

interface Props {
  selectedOrderId?: string
}

const props = withDefaults(defineProps<Props>(), {
  selectedOrderId: ''
})

const emit = defineEmits(['getOrderCreditDetail'])

// 订单详情回显数据
const orderDetailData = ref<any>(null)
// 添加 loading 状态
const loading = ref(false)

// 回款状态枚举
const repaymentStatusEnum = {
  0: '未回款',
  1: '已回款',
  2: '回款中'
} as Record<number, string>

// 餐厅名称
const shopName = computed(() =>
  fetchObjectDeepAttrValue(orderDetailData.value, 'detail.shopInfo.shop_name', '')
)
// 餐厅电话
const shopPhone = computed(() =>
  fetchObjectDeepAttrValue(orderDetailData.value, 'detail.shopInfo.phone', '')
)
// 餐厅地址
const shopAddress = computed(() =>
  fetchObjectDeepAttrValue(orderDetailData.value, 'detail.shopInfo.address', '')
)
// 订单编号
const orderId = computed(() => dealAssignDataFunction('', orderDetailData.value?.order_id))
// 收银员
const clerkName = computed(() =>
  fetchObjectDeepAttrValue(orderDetailData.value, 'detail.clerkName', '')
)
// 账户名称
const accountName = computed(() => dealAssignDataFunction('', orderDetailData.value?.name))
// 回款金额
const money = computed(() => dealAssignDataFunction(0, orderDetailData.value?.money))
// 支付方式

// 支付方式
const payMethod = () => {
  let payInfo = fetchObjectDeepAttrValue(orderDetailData.value, 'detail.payInfo', [])
  let credit_list = fetchObjectDeepAttrValue(orderDetailData.value, 'detail.credit_list', [])
  if (payInfo.length > 0 && credit_list.length == 0) {
    return '挂账支付'
  }

  let payMethod = [...payInfo, ...credit_list]
  if (payMethod.length > 1) return '混合支付'
  return payMethod[0].name
}

// const payMethod = computed(() => dealAssignDataFunction('', orderDetailData.value?.describe))
// 回款状态
const repaymentStatus = computed(() => {
  const status = dealAssignDataFunction(0, orderDetailData.value?.repayment_status)
  return repaymentStatusEnum[status] || '未知'
})
// 回款时间
const createTime = computed(() => dealAssignDataFunction('', orderDetailData.value?.create_time))
// 回款人
const repaymentUser = computed(() =>
  dealAssignDataFunction('', orderDetailData.value?.order?.user_name)
)
// 备注
const remark = computed(() => dealAssignDataFunction('', orderDetailData.value?.remark))

// 辅助映射
const deskListExists = computed(() => !!orderDetailData.value?.detail?.deskList)
const foodListExists = computed(() => !!orderDetailData.value?.detail?.foodList)
const priceInfo = computed(() =>
  dealAssignDataFunction({ serviceMoney: 0, payMoney: 0 }, orderDetailData.value?.detail?.priceInfo)
)
const payInfo = computed(() => dealAssignDataFunction([], orderDetailData.value?.detail?.payInfo))
const creditList = computed(() =>
  dealAssignDataFunction([], orderDetailData.value?.detail?.credit_list)
)

// 支付方式枚举（显示“实收明细”）
const payMethodEnum: Record<string, string> = {
  balance: '余额',
  cash: '现金',
  on_account1: '企业挂账',
  on_account2: '个人挂账',
  integripay: '积分支付'
}

// 处理多个桌台回显
const computedDeskName = computed(() => {
  const list = orderDetailData.value?.detail?.deskList || []
  if (list.length) {
    return list.map((desk: any) => `${desk.name}(${desk.use_num}人)`).join('、')
  }
  return ''
})

// 处理回显菜品的规格信息（做法+口味+部位）
const dealFoodSkuDescFun = (item: any) => {
  if (item?.notes?.length) {
    return item.notes.join('、')
  } else {
    return false
  }
}
// 获取订单详情
watch(
  () => props.selectedOrderId,
  async newVal => {
    if (!newVal) {
      orderDetailData.value = null
      loading.value = false
      return
    }
    loading.value = true
    try {
      const res: any = await orderCreditDetail({ order_id: newVal })
      if (res?.status === 200) {
        // 老项目该接口直接返回 detail 结构
        orderDetailData.value = dealAssignDataFunction(null, res?.data.detail)
        emit('getOrderCreditDetail', orderDetailData.value)
      } else {
        orderDetailData.value = null
      }
    } finally {
      loading.value = false
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
// 骨架屏容器样式
.skeleton-container {
  width: 100%;
  height: 100%;
  padding: 20px 0;

  :deep(.el-skeleton) {
    .el-skeleton__item {
      background: #f5f5f5;
      border-radius: 4px;
    }

    .el-skeleton__text {
      height: 16px;
      margin-top: 8px;
    }
  }
}

.onAccount-card-box {
  overflow-y: auto;
  overflow-x: hidden;
  width: 420px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  box-shadow: 3px 0px 24px 0px rgba(0, 0, 0, 0.16);
  box-sizing: border-box;
  padding: 30px;
  transition: all 1s !important;

  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #333333;
  }

  .description {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #333333;
    margin: 10px 0;
  }

  .desc-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }

  .desc-item-box {
    display: flex !important;
    align-items: center !important;
    justify-content: space-between !important;
  }

  .desc-line {
    width: 360px;
    height: 1px;
    background: #e2e2e2;
    margin-top: 10px;
  }

  .address-phone-box {
    margin-top: 50px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #333333;
    line-height: 24px;
    > div {
      margin-bottom: 10px;
    }
  }

  .good-list-box {
    margin-top: 10px;
    .good-item {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      color: #000000;
      text-align: center;
      .good-name {
        width: 70px;
      }
      > div {
        &:last-child {
          text-align: right;
        }
        &:first-child {
          text-align: left;
        }
      }
    }
    .good-sku-item {
      margin-top: 8px;
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      color: #000000;
      line-height: 18px;
    }
  }

  .lineHeight20 {
    line-height: 20px;
  }
}

.show {
  display: block !important;
  width: 420px !important;
  transition: all 1s !important;
}
.hide {
  display: none !important;
  transition: all 1s !important;
}
</style>
